package com.gzdh.dishrecognition.ui.dialog;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.greendao.dao.BQEntityDao;
import com.greendao.dao.KSEntityDao;
import com.gzdh.dishrecognition.AppContext;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.entity.BQEntity;
import com.gzdh.dishrecognition.entity.KSEntity;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

public class PopupWindowDiningTable extends PopupWindow {
    private static final String TAG = "PopupWindowRight";

    private Context context;

    private BQEntityDao bqEntityDao;

    private KSEntityDao ksEntityDao;

    private LinearLayout startTimeBut;
    private LinearLayout endTimeBut;

    private TextView endTimeTv;
    private TextView startTimeTv;
    private EditText nameEdit;

    private Spinner bqSpinner;

    private Spinner ksSpinner;
    private UserSubmit userSubmit;

    private TextView okBut;

    private String bqh;

    private String ksh;

    public void setUserSubmit(UserSubmit userSubmit) {
        this.userSubmit = userSubmit;
    }

    public String getName(){
        return nameEdit.getText().toString();
    }

    public String getBqh(){
        return bqh;
    }
    public String getKsh(){
        return ksh;
    }

    public PopupWindowDiningTable(Context context, View popupWindowView) {
        //设置view
        this.context = context;
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.popup_dining_table, null);
        setContentView(view);
        initView(view);
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        //activity的contentView的高度
        int height = ((Activity) context).findViewById(android.R.id.content).getHeight();
        //其他设置
        WindowManager.LayoutParams attributes = ((Activity) context).getWindow().getAttributes();
        attributes.alpha = 0.5f;
        ((Activity) context).getWindow().setAttributes(attributes);
        setWidth(WindowManager.LayoutParams.WRAP_CONTENT);

        setHeight(height);//必须设置高度
        setFocusable(false);//是否获取焦点
        setOutsideTouchable(true);//是否可以通过点击屏幕外来关闭
        ViewTreeObserver vto = view.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int height = view.getHeight();
                int width = view.getWidth();
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        //加入动画
        ObjectAnimator.ofFloat(getContentView(), "translationX", getWidth(), 0).setDuration(500).start();
    }

    /**
     * 获取屏幕宽高
     *
     * @param context
     * @return
     */
    private static int[] getScreenSize(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return new int[]{displayMetrics.widthPixels, displayMetrics.heightPixels};
    }

    /**
     * Value of dp to value of px.
     *
     * @param dpValue The value of dp.
     * @return value of px
     */
    public static int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private void initView(View view) {
        startTimeBut = view.findViewById(R.id.startTimeBut);
        endTimeBut = view.findViewById(R.id.endTimeBut);
        endTimeTv = view.findViewById(R.id.endTimeTv);
        endTimeTv.setText(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()));

        startTimeTv = view.findViewById(R.id.startTimeTv);
        startTimeTv.setText(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()));
        nameEdit = view.findViewById(R.id.nameEdit);

        bqEntityDao = AppContext.getInstance().getDaoSession().getBQEntityDao();
        List<BQEntity> bqList = bqEntityDao.loadAll();
        ksEntityDao = AppContext.getInstance().getDaoSession().getKSEntityDao();
        List<KSEntity> ksList = ksEntityDao.loadAll();

        bqSpinner = view.findViewById(R.id.bqSpinner);
        bqSpinner.setPrompt("请选择区");
        List<Type> list = new ArrayList<>();
        list.add(new Type("全部", "0000"));
        for (BQEntity bqEntity : bqList) {
            list.add(new Type(bqEntity.getName(), bqEntity.getBm()));
        }
        ArrayAdapter<Type> adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list);
        bqSpinner.setAdapter(adapter);
        bqSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                Type type = (Type) adapterView.getItemAtPosition(position);
                bqh = type.getBm();
                ksh = "0000";
                if(!bqh.equals("0000")) {
                    List<KSEntity> filterList = ksList.stream().filter(v -> v.getBqh().equals(bqh)).collect(Collectors.toList());
                    List<Type> ksType = new ArrayList<>();
                    ksType.add(new Type("全部", "0000"));
                    for (KSEntity ksEntity : filterList) {
                        ksType.add(new Type(ksEntity.getName(), ksEntity.getBm()));
                    }
                    ksSpinner.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, ksType));
                } else {
                    List<Type> ksType = new ArrayList<>();
                    ksType.add(new Type("全部", "0000"));
                    for (KSEntity ksEntity : ksList) {
                        ksType.add(new Type(ksEntity.getName(), ksEntity.getBm()));
                    }
                    ksSpinner.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, ksType));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        ksSpinner = view.findViewById(R.id.ksSpinner);
        ksSpinner.setPrompt("请选择餐桌");
        list = new ArrayList<>();
        list.add(new Type("全部", "0000"));
        for (KSEntity ksEntity : ksList) {
            list.add(new Type(ksEntity.getName(), ksEntity.getBm()));
        }
        adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list);
        ksSpinner.setAdapter(adapter);
        ksSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                Type type = (Type) adapterView.getItemAtPosition(position);
                ksh = type.getBm();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        okBut = view.findViewById(R.id.okBut);
        startTimeBut.setOnClickListener(view1 -> {
            Calendar mcalendar = Calendar.getInstance(); // 获取当前时间 — 年、月、日
            int year = mcalendar.get(Calendar.YEAR); // 得到当前年
            int month = mcalendar.get(Calendar.MONTH); // 得到当前月
            final int day = mcalendar.get(Calendar.DAY_OF_MONTH); // 得到当前日
            new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() { // 日期选择对话框
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    startTimeTv.setText(year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth));
                }
            }, year, month, day).show(); // 弹出日历对话框时，默认显示 年，月，日
        });

        endTimeBut.setOnClickListener(view1 -> {
            Calendar mcalendar = Calendar.getInstance(); // 获取当前时间 — 年、月、日
            int year = mcalendar.get(Calendar.YEAR); // 得到当前年
            int month = mcalendar.get(Calendar.MONTH); // 得到当前月
            final int day = mcalendar.get(Calendar.DAY_OF_MONTH); // 得到当前日
            new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() { // 日期选择对话框
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    endTimeTv.setText(year + "-" + String.format("%02d", month + 1) + "-" + String.format("%02d", dayOfMonth));
                }
            }, year, month, day).show(); // 弹出日历对话框时，默认显示 年，月，日
        });
        okBut.setOnClickListener(view1 -> {
            if (userSubmit != null) {
                String name = nameEdit.getText().toString();
                userSubmit.onUserSubmit(startTimeTv.getText().toString(), endTimeTv.getText().toString(), name, bqh, ksh);
            }
            dismiss();
        });

    }

    @Override
    public void dismiss() {
        WindowManager.LayoutParams attributes = ((Activity) context).getWindow().getAttributes();
        attributes.alpha = 1f;
        ((Activity) context).getWindow().setAttributes(attributes);
        super.dismiss();
    }

    public interface UserSubmit {
        public void onUserSubmit(String startTime, String endTime, String name, String bqh, String ksh);
    }

    public static class Type implements Serializable {

        public Type(String name, String bm) {
            this.name = name;
            this.bm = bm;
        }

        private static final long serialVersionUID = 1L;

        private String name;

        private String bm;


        public static long getSerialVersionUID() {
            return serialVersionUID;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getBm() {
            return bm;
        }

        public void setBm(String bm) {
            this.bm = bm;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}
